﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using hedefgrup.reports.renault.date;
using hedefgrup.reports.renault.implementation;
using hedefgrup.reports.renault;
using System.Text;
using hedefgrup.reports.renault.definitions;
using System.Collections.Generic;
using hedefgrup.reports.renault.calculators;

public partial class totalResults : reportPage
{
    private const string EMPTY_CELL_TEMPLATE = "<td NOWRAP class=chead {0}></td>";
    private const string HEADER_TEMPLATE = "<td nowrap class=chead {0}>{1} {2}</td>";
    private const string SUB_HEADER_TEMPLATE = "<td nowrap class=vktxt8>{0}-{1}</td>";

    private const string HEADER_TEMPLATE_2 = "<td nowrap class=chead2 style='height:1px;' {0}>{1} {2}</td>";
    private const string SUB_HEADER_TEMPLATE_2 = "<td nowrap class=vktxt9>{0}-{1}</td>";

    private const string DEALER_TEMPLATE = "<tr><td nowrap class=chead2 style='width:45px'>{0}</td><td nowrap class=chead2 style='width:155px'>{1}</td></tr>";
    private const string FORMAT_CELL = "<td class=ccol>{0}</td>";
    private const string FORMAT_IMPORTANT_CELL = "<td class=ccolimp>{0}</td>";

    private StringBuilder emptyRowHtmlBuilder;

    private reportDealerInfo[] generatedReport;

    protected override string getReportFileName()
    {
        return "BAYII ANALIZ - " + base.getReportFileName();
    }

    private void writeTableHeader(string headerTemplate, string subHeaderTemplate, Literal headerLiteral, Literal subHeaderLiteral, string prefix, string suffix)
    {
        StringBuilder tableHeaderBuilder = new StringBuilder();
        StringBuilder tableSubHeaderBuilder = new StringBuilder();
        emptyRowHtmlBuilder = new StringBuilder("<tr>");

        reportDefinition totalReport = base.getDataCache().reportDefinitions["total_report"];

        foreach (reportRowDefinition row in totalReport.rowDefinitions)
        {
            questionDefinition questionToReport = null;

            switch (row.getRowType())
            {
                case Global.PROJECT_QVN:
                    questionToReport = base.getDataCache().questionDefinitions[row.getQuestionToReport()];
                    tableHeaderBuilder.AppendFormat(headerTemplate, "", questionToReport.getCode(), questionToReport.getName());
                    emptyRowHtmlBuilder.AppendFormat(EMPTY_CELL_TEMPLATE, "");
                    tableSubHeaderBuilder.AppendFormat(subHeaderTemplate, questionToReport.optionDefinitions.Values[0].getValue(), questionToReport.optionDefinitions.Values[0].getText());
                    break;
                case "percentage":
                    questionToReport = base.getDataCache().questionDefinitions[row.getQuestionToReport()];
                    tableHeaderBuilder.AppendFormat(headerTemplate, "colspan=" + questionToReport.optionDefinitions.Count, questionToReport.getCode(), questionToReport.getName());
                    emptyRowHtmlBuilder.AppendFormat(EMPTY_CELL_TEMPLATE, "colspan=" + questionToReport.optionDefinitions.Count);
                    foreach (optionDefinition opt in questionToReport.optionDefinitions.Values)
                    {
                        tableSubHeaderBuilder.AppendFormat(subHeaderTemplate, opt.getValue(), opt.getText());
                    }
                    break;
                case "formula_2":
                case "formula_1":
                    questionToReport = base.getDataCache().questionDefinitions[row.getQuestionToReport()];
                    tableHeaderBuilder.AppendFormat(headerTemplate, "", questionToReport.getCode(), questionToReport.getName());
                    emptyRowHtmlBuilder.AppendFormat(EMPTY_CELL_TEMPLATE, "");
                    tableSubHeaderBuilder.AppendFormat(subHeaderTemplate, "%", "ORAN");
                    break;
                case "percentage_over_total_base":
                    tableHeaderBuilder.AppendFormat(headerTemplate, "", row.getAttributeByName("h"), "");
                    emptyRowHtmlBuilder.AppendFormat(EMPTY_CELL_TEMPLATE, "");
                    tableSubHeaderBuilder.AppendFormat(subHeaderTemplate, "", "");
                    break;
                case "base":
                    tableHeaderBuilder.AppendFormat(headerTemplate, "", "Baz", "");
                    emptyRowHtmlBuilder.AppendFormat(EMPTY_CELL_TEMPLATE, "");
                    tableSubHeaderBuilder.AppendFormat(subHeaderTemplate, "", "");
                    break;

            }
        }
        emptyRowHtmlBuilder.Append("</tr>");
        if (headerLiteral != null) { headerLiteral.Text += prefix + tableHeaderBuilder.ToString() + suffix; }
        if (subHeaderLiteral != null) { subHeaderLiteral.Text += prefix + tableSubHeaderBuilder.ToString() + suffix; }
    }

    private void writeDealers()
    {
        StringBuilder dealerHtmlBuilder = new StringBuilder();

        foreach (reportDealerInfo dealerInfo in generatedReport)
        {
            if (dealerInfo.data.baseCount > 0)
            {
                List<string> userDealerCodes = new List<string>(base.getUserDealerCodes());
                if (userDealerCodes.Count == 0 || userDealerCodes.Contains(dealerInfo.dealer.getCode()) || dealerInfo.dealer.isParentOfAny(base.getUserDealerCodes()))
                {
                    dealerHtmlBuilder.AppendFormat(DEALER_TEMPLATE, dealerInfo.dealer.getCode(), dealerInfo.dealer.getName());
                }
            }
        }
        dealersHtml.Text = dealerHtmlBuilder.ToString();
    }

    protected static string getCellTemplate(reportRowDefinition row, optionDefinition opt)
    {
        return
            opt != null && row.getAttributeByName("io") == opt.getValue().ToString()
            ||
            opt == null && row.getAttributeByName("i") == "true"
            ?
                FORMAT_IMPORTANT_CELL
            :
                FORMAT_CELL
        ;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        base.initialize();
        base.ensureUserIsLoggedIn();

        excelReportName.Text = base.getReportFileName();

        excelExportDiv.Visible = !IsExcelDownloadRequest;

        generatedReport = base.getCalculator().generateReportDataForMultipleDealers(base.calculationType, base.selectedMonth - (base.cumulativeMonths - 1), base.selectedMonth);

        writeTableHeader(HEADER_TEMPLATE, SUB_HEADER_TEMPLATE, tableHeaderHtml, tableSubHeaderHtml, "", "");
        writeDealers();

        reportDefinition totalReport = base.getDataCache().reportDefinitions["total_report"];

        StringBuilder reportHtmlBuilder = new StringBuilder();

        foreach (reportDealerInfo dlrInfo in generatedReport)
        {
            if (dlrInfo.data.baseCount <= 0) continue;
            List<string> userDealerCodes = new List<string>(base.getUserDealerCodes());
            if (userDealerCodes.Count == 0 || userDealerCodes.Contains(dlrInfo.dealer.getCode()) || dlrInfo.dealer.isParentOfAny(base.getUserDealerCodes()))
            {
                StringBuilder rowBuilder = new StringBuilder();
                foreach (reportRowDefinition row in totalReport.rowDefinitions)
                {
                    cumulativeData dataToReport = dlrInfo.data;
                    questionDefinition questionToReport = null;
                    question questionDataToReport = null;
                    if (row.getRowType() != "base")
                    {
                        questionToReport = base.getDataCache().questionDefinitions[row.getQuestionToReport()];
                        questionDataToReport = dataToReport.questions[questionToReport.getCode()];
                    }
                    switch (row.getRowType())
                    {
                        case Global.PROJECT_QVN:
                            rowBuilder.AppendFormat(getCellTemplate(row, null), (questionDataToReport.calculateQvn() * 100).ToString("0.0"));
                            break;
                        case "percentage":
                            foreach (optionDefinition opt in questionToReport.optionDefinitions.Values)
                            {
                                rowBuilder.AppendFormat(getCellTemplate(row, opt), (questionDataToReport.calculateOptionPercentage(opt.getValue()) * 100).ToString("0.0"));
                            }
                            break;
                        case "formula_2":
                            rowBuilder.AppendFormat(getCellTemplate(row, null), (questionDataToReport.calculateFormula2() * 100).ToString("0.0"));
                            break;
                        case "formula_1":
                            rowBuilder.AppendFormat(getCellTemplate(row, null), (questionDataToReport.calculateFormula1() * 100).ToString("0.0"));
                            break;
                        case "percentage_over_total_base":
                            double value = 0;
                            string[] optionsToReport = row.getAttributeByName("o").Split(',');
                            foreach (string optionToReportString in optionsToReport)
                            {
                                int optionToReport = Convert.ToInt32(optionToReportString);
                                value += questionDataToReport.getOptionCount(optionToReport);
                            }
                            rowBuilder.AppendFormat(getCellTemplate(row, null), (value * 100 / dataToReport.baseCount).ToString("0.0"));
                            break;
                        case "base":
                            rowBuilder.AppendFormat(getCellTemplate(row, null), dataToReport.baseCount);
                            break;

                    }
                }
                reportHtmlBuilder.AppendFormat("<tr onmouseover='show(this)' onmouseout='sout(this)'>{0}</tr>", rowBuilder);
            }
        }

        reportHtml.Text = emptyRowHtmlBuilder.ToString() + reportHtmlBuilder.ToString();

        writeTableHeader(HEADER_TEMPLATE_2, SUB_HEADER_TEMPLATE_2, null, reportHtml, "<tr>", "</tr>");

        base.RenderComplete();

        renderElapsedTime.Text = base.getElapsedRenderTime().ToString();
    }
}
